package net.stancristian.restnews;

import java.util.ArrayList;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.json.JSONArray;
import org.json.JSONException;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.ListView;

public class AdminActivity extends Activity {

	private RestNewsApplication app;
	private ListView userList;
	private ArrayList<UserIdentity> users;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_admin);
		app = (RestNewsApplication) getApplicationContext();
		userList = (ListView) findViewById(R.id.listViewUsers);
		users = new ArrayList<UserIdentity>();
		InitUserList();
	}

	/*
	 * Init the list
	 */
	private void InitUserList() {
		String baseApiAddress = getString(R.string.api_base_address);
		String Url = baseApiAddress + "/User?getAll=true";

		HttpResponse response = RestNewsClient.getRequestWebService(Url);
		if (response != null
				&& response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
			try {
				JSONArray array = RestNewsClient
						.GetJsonArrayFromResponse(response);

				for (int i = 0; i < array.length(); i++) {
					users.add(new UserIdentity(array.getJSONObject(i)));
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}

		UserIdentityAdapter adapter = new UserIdentityAdapter(this, users.toArray(new UserIdentity[(users.size())]));
		userList.setAdapter(adapter);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.admin, menu);
		return true;
	}

}
